﻿using Prism.Mvvm;
using HandyControl.Controls;
using System.Windows;
using IntoTheVoid.Models;
using Prism.Commands;
using System.Diagnostics;
using IntoTheVoid.Units;
using System.Windows.Controls;
using System.Windows.Data;
using System.Globalization;
using System;
using IntoTheVoid.Views;
using System.ComponentModel;
using System.Text.RegularExpressions;
using System.Windows.Input;
using IntoTheVoid.Units.DownloadEventArgs;
using System.IO;
using System.Windows.Shapes;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Dialogs;
using Microsoft.Win32;
using static System.Net.Mime.MediaTypeNames;
using System.Web.UI.WebControls;
using IntoTheVoid.State;
using System.Runtime.Remoting.Contexts;
using System.Runtime.CompilerServices;

namespace IntoTheVoid.ViewModels
{
	class SettingViewModel : BindableBase
	{
		public event PropertyChangedEventHandler PropertyChange;
		private void OnPropertyChanged(string p_propertyName)
		{
			if (PropertyChange != null)
			{
				PropertyChange(this, new PropertyChangedEventArgs(p_propertyName));
			}
		}

		private TabEnum currentTabSet = TabEnum.CommonSetting;
		public TabEnum CurrentTabSet
		{
			get
			{
				return currentTabSet;
			}

			set
			{
				currentTabSet = value;
				// OnPropertyChanged("SampleEnum");
			}
		}


		private bool isAutoStart;
		public bool IsAutoStart
		{
			get { return isAutoStart; }
			set { isAutoStart = value; RaisePropertyChanged(); }
		}
		private bool isAutoOpenGame;
		public bool IsAutoOpenGame
		{
			get { return isAutoOpenGame; }
			set { isAutoOpenGame = value; RaisePropertyChanged(); }
		}

		private int iCloseWindowType;
		public int ICloseWindowType
		{
			get { return iCloseWindowType; }
			set { iCloseWindowType = value; RaisePropertyChanged(); }
		}
		// 是否限速
		private int iIsDownLoadUnlimitedSpeed;
		public int IIsDownLoadUnlimitedSpeed
		{
			get { return iIsDownLoadUnlimitedSpeed; }
			set { iIsDownLoadUnlimitedSpeed = value; RaisePropertyChanged(); }
		}
		// 修改下载文件夹按钮是否可用
		private bool iIsChangeDownloadFilterEnable = true;
		public bool IIsChangeDownloadFilterEnable
		{
			get { return iIsChangeDownloadFilterEnable; }
			set { iIsChangeDownloadFilterEnable = value; RaisePropertyChanged(); }
		}
		// 清理游戏文件按钮是否可用
		private bool iIsClearGameFileEnable = true;
		public bool IIsClearGameFileEnable
		{
			get { return iIsClearGameFileEnable; }
			set { iIsClearGameFileEnable = value; RaisePropertyChanged(); }
		}
		// 限速单位 kb/s
		private int iDownLoadLimitedSpeed = 4096;
		public int IDownLoadUnlimitedSpeed
		{
			get { return iDownLoadLimitedSpeed; }
			set { iDownLoadLimitedSpeed = value; RaisePropertyChanged(); }
		}
		// 安装路径
		private string iInstallPathText;
		public string IInstallPathText
		{
			get { return iInstallPathText; }
			set { iInstallPathText = value; RaisePropertyChanged(); }
		}
		// 当前版本
		private string versionString = "";
		public string VersionString
		{
			get { return versionString; }
			set
			{
				versionString = value;
				RaisePropertyChanged();
			}
		}
		private BaseInfoContentModel baseInfoContentModel;
		public Dialog ParentDialog { get; set; }

		public DelegateCommand SaveDataCommand { get; private set; }
		public DelegateCommand OpenLogsCommand { get; private set; }
		public DelegateCommand UpdateLauncherCommand { get; private set; }
		public DelegateCommand ChooseInstallPathCommand { get; private set; }
		public DelegateCommand ClearGamePathFile { get; private set; }
		public DelegateCommand<string> CloseWindowTypeCommond { get; private set; }
		public DelegateCommand RecoverInstallPathCommand { get; private set; }

		public event EventHandler<DownloadSpeedChangetArgs> ChangeDownloadSpeed;
		public event EventHandler DeleteGameInfoFiles;

		public SettingViewModel()
		{
			VersionString = "当前版本：" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();

			baseInfoContentModel = BaseInfoContentModel.Instance;
			SaveDataCommand = new DelegateCommand(SaveData);
			OpenLogsCommand = new DelegateCommand(OpenLogsDialog);
			UpdateLauncherCommand = new DelegateCommand(UpdateLaucher);
			ChooseInstallPathCommand = new DelegateCommand(ChoosePath);
			ClearGamePathFile = new DelegateCommand(ClearInfoPath);
			CloseWindowTypeCommond = new DelegateCommand<string>(CloseWindowType);
			RecoverInstallPathCommand = new DelegateCommand(RecoverPath);

			SetCloseWindowType();
			SetAutoStart();
			SetDownloadSpeed();
			SetAutoOpenGameLauncherShow();
			SetInstallPath();
			
		}

		private void SetDownloadSpeed()
		{
			var speed = baseInfoContentModel.GetValue<int>("setDownloadSpeed", -1);
			iIsDownLoadUnlimitedSpeed = speed == -1 || speed == 0 ? 1 : 0;
			if (speed > 0)
			{
				IDownLoadUnlimitedSpeed = speed;
			}
		}
		private void SaveDownloadSpeed()
		{
			bool limit = false;
			if (iIsDownLoadUnlimitedSpeed == 1)
			{
				baseInfoContentModel.SetValue("setDownloadSpeed", -1);
			}
			else
			{
				if (iDownLoadLimitedSpeed > 0)
				{
					iDownLoadLimitedSpeed = Math.Min(40960, iDownLoadLimitedSpeed);
					iDownLoadLimitedSpeed = Math.Max(100, iDownLoadLimitedSpeed);
				}
				limit = true;
				baseInfoContentModel.SetValue("setDownloadSpeed", iDownLoadLimitedSpeed);
			}
			ChangeDownloadSpeed?.Invoke(this, new DownloadSpeedChangetArgs(limit, iDownLoadLimitedSpeed));
		}

		private void SetInstallPath()
		{
			var basePath = AppDomain.CurrentDomain.BaseDirectory;
			var defaultPath = System.IO.Path.Combine(basePath, "Game");
			var path = baseInfoContentModel.GetValue<string>("gameInstallPath", null);
			if (path == "" || path == null)
			{
				path = Common.GetGameInstallPathReg();
				if (path == "" || path == null)
				{
					path = defaultPath;
				}
			}
			Common.SaveInstallPath(path);
			IInstallPathText = path;
		}
		private void SaveInstallPath()
		{
			Common.SaveInstallPath(IInstallPathText);
		}


		private void SetCloseWindowType()
		{
			var typ = baseInfoContentModel.GetValue<int>("setCloseWindowType", 0);
			ICloseWindowType = typ;
		}
		private void SaveCloseWindowType()
		{
			baseInfoContentModel.SetValue("setCloseWindowType", ICloseWindowType);
		}

		private void SetAutoStart()
		{
			var autoOpenGameLauncherSign = baseInfoContentModel.GetValue<int>("autoEnableStartUp", 0);
			IsAutoStart = autoOpenGameLauncherSign == 0;
		}
		private void SaveAutoStart()
		{
			var autoOpenGameLauncherSign = IsAutoStart ? 0 : 1;
			baseInfoContentModel.SetValue("autoEnableStartUp", autoOpenGameLauncherSign);
		}

		private void SetAutoOpenGameLauncherShow()
		{
			var autoOpenGameLauncherSign = baseInfoContentModel.GetValue<int>("autoOpenGameLauncher", 1);
			IsAutoOpenGame = autoOpenGameLauncherSign == 1;
		}
		private void SaveAutoOpenGameLauncherShow()
		{
			var autoOpenGameLauncherSign = isAutoOpenGame ? 1 : 0;
			baseInfoContentModel.SetValue("autoOpenGameLauncher", autoOpenGameLauncherSign);
		}

		private void SaveData()
		{
			SaveCloseWindowType();
			SaveAutoStart();
			SaveAutoOpenGameLauncherShow();
			SaveDownloadSpeed();
			SaveInstallPath();
			MainViewModel.stateContext.CurState = new FirstCheckState(MainViewModel.stateContext, true);
			MainViewModel.stateContext.CurState.Start(MainViewModel.stateContext);
			ParentDialog.Close();
		}
		private void ChoosePath()
		{
			var dialog = new CommonOpenFileDialog(IInstallPathText);
			dialog.IsFolderPicker = true;
			CommonFileDialogResult result = dialog.ShowDialog();
			if (result == CommonFileDialogResult.Ok)
			{
				var fileName = System.IO.Path.Combine(dialog.FileName, "IntoTheVoid");
				IInstallPathText = fileName;
				// baseInfoContentModel.SetValue("gameInstallPath", IInstallPathText);
			}

		}
		bool bForCheck = false;
		private void UpdateLaucher()
		{
			// 版本检测更新
			bForCheck = true;
			var gameDownlaodConifgModel = GameDownloadConfigModel.Instance;
			gameDownlaodConifgModel.DownLoadConfigCompleted += DownLoadConfigCompleted;
			gameDownlaodConifgModel.SendStartConfigMessage(baseInfoContentModel.GetValue<string>("version", ""));

		}
		private void DownLoadConfigCompleted(object sender, GameDownloadConfigEventArgs e)
		{
			if (!bForCheck)
			{
				return;
			}
			bForCheck = false;
			var info = GameDownloadConfigModel.Instance.DownLoadInfo;
			if(info == null)
			{
				var view = new TipView("获取版本更新失败，请稍后再试", () => Environment.Exit(0), () => Environment.Exit(0));
				return;
			}
			if (!Common.CheckLauncherVersion(info.LauncherLatest))
			{
				Action confirmAction = () =>
				{
					Common.OpenLauncherUpdate(info.LauncherLink);
				};
				App.Current.Dispatcher.Invoke((Action)(() =>
				{
					var view = new TipView("启动器更新：修复了部分问题", confirmAction, () => Environment.Exit(0));
					var dialog = Dialog.Show(view);
					var viewModel = (dialog.Content as TipView).DataContext as TipViewModel;
					viewModel.ParentDialog = dialog;
				}));
			}
			else
			{
				App.Current.Dispatcher.Invoke((Action)(() =>
				{
					var view = new TipView("当前已是最新版本");
					var dialog = Dialog.Show(view);
					var viewModel = (dialog.Content as TipView).DataContext as TipViewModel;
					viewModel.ParentDialog = dialog;
				}));
			}
		}
		private void OpenLogsDialog()
		{
			String path = Environment.CurrentDirectory + "/Logs";

			if (!Directory.Exists(path))
			{
				try
				{
					Directory.CreateDirectory(path);
				}
				catch (Exception e)
				{
					LogHelper.Error("Logs Filter Create Error" + e.Message);
				}
			}
			Process.Start(path);
		}
		private void ClearInfoPath()
		{
			// 清理游戏系统文件+游戏下载文件
			DeleteGameInfoFiles?.Invoke(this, null);
			SetCloseWindowType();
			SetAutoStart();
			SetDownloadSpeed();
			SetAutoOpenGameLauncherShow();
			SetInstallPath();
		}
		private void CloseWindowType(string typ)
		{
			iCloseWindowType = int.Parse(typ);
		}


		private void RecoverPath()
		{
			var basePath = AppDomain.CurrentDomain.BaseDirectory;
			var defaultPath = System.IO.Path.Combine(basePath, "Game\\");
			baseInfoContentModel.SetValue("gameInstallPath", defaultPath);
			IInstallPathText = defaultPath;

		}
	}
}
